package ee.battleship.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.org.apache.bcel.internal.generic.RET;

import ee.battleship.classes.Player;

/**
 * Servlet Filter implementation class UserLogin
 */
@WebFilter(filterName="UserLogin",urlPatterns={"/Index", "/*"})
public class UserLogin implements Filter {

    /**
     * Default constructor. 
     */
    public UserLogin() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		
		String fileName = "";
		
		int i = req.getRequestURI().lastIndexOf('/');
		
		if (i > -1) {
			fileName = req.getRequestURI().substring(i);
		}
		
		request.setCharacterEncoding("UTF-8");
//		resp.addHeader("Expires", "-1"); // forever?
		
		if (fileName.equals("/lobby.jsp")) {
			if(session.getAttribute("player") == null) {
				RequestDispatcher r = req.getRequestDispatcher("/index.jsp");
				r.forward(req, resp);
				return;
			}
		}
		
		if (fileName.equals("/game.jsp")) {
			if (session.getAttribute("player") == null) {
				RequestDispatcher r = req.getRequestDispatcher("/index.jsp");
				r.forward(req, resp);
				return;
			}
			
			if (session.getAttribute("game") == null && session.getAttribute("player") != null) {
				RequestDispatcher r = req.getRequestDispatcher("/lobby.jsp");
				r.forward(req, resp);
				return;
			}
		}
		
		if (fileName.equals("/index.jsp") || fileName.equals("/") || fileName.equals("/Index")) {
			if (session.getAttribute("player") != null) {	
				RequestDispatcher r = req.getRequestDispatcher("/lobby.jsp");
				r.forward(req, resp);
				return;
			}
		}
		
		chain.doFilter(request, response);
	}
	
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
